﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using Indigo.Quibbler.Data;
using Indigo.Quibbler.Controls;
using System.Windows.Threading;
using System.Windows.Media.Media3D;
using System.Collections;
using System.Collections.ObjectModel;

using Indigo.Quibbler.Library;
using System.Xml;
using System.IO;
using System.Diagnostics;
using Indigo.Quibbler.Common;
using Indigo.Quibbler.Properties;
using System.ComponentModel;
using System.Net;

namespace Indigo.Quibbler {
    public enum ViewWindow {
        None, Sections, ArticlesList, ArticleGallery,
        SpiderSearch, SpiderRelated, SpiderPhotoRelated,
        PhotoGallery, PhotoGalleryRelated,
        VideoGallery,
        ArticleGalleryRelated, ArticleGallerySearch
    }

    public partial class EditionWindow : QuibblerWindow {
        #region Constants
        private string ONLINE_SEARCH_URL = "http://timesofindia.indiatimes.com/search.cms?q={0}";
        #endregion

        #region Private Members
        private DispatcherTimer _updateTimer = new DispatcherTimer();
        private bool _isUpdateInProgress = false;
        private DispatcherTimer _lastUpdateTimer = new DispatcherTimer();
        private int _lastUpdateTime = 0;
        private bool _isOnline = false;
        private DispatcherTimer _loadInitiaterTimer = new DispatcherTimer();
        private DispatcherTimer _addCategoryTimer = new DispatcherTimer();

        private List<NewsArticle> _articles = new List<NewsArticle>();
        private string _publicationDate = String.Empty;
        private ViewType _lastSectionViewType = ViewType.Tile;
        private ViewType _lastArticlesListViewType = ViewType.Tile;
        private bool _isTransitionsOngoing = false;

        private bool _isUnavailabilityShown = false;
        private bool _isSearchModeOn = false;
        private string _searchTerm = String.Empty;

        private List<NewsSection> _listNewsSections = new List<NewsSection>();
        private List<string> _listMainCategories = new List<string>();
        private List<string> _listSubCategories = new List<string>();
        private List<NewsArticle> _listArticlesinAccordion = new List<NewsArticle>();
        private List<NewsArticle> _listSelectedCategoryNewsArticles = new List<NewsArticle>();
        private List<string> _listPhotos = new List<string>();
        private Dictionary<string, string> _mappedAccordionCategories = new Dictionary<string, string>();
        private List<NewsArticle> _listCurrentPhotoGalleryArticles = new List<NewsArticle>();
        private List<NewsArticle> _listCurrentVideoGalleryArticles = new List<NewsArticle>();
        private List<string> _listOfCitiesAvailable = new List<string>();

        private int _selectedCategoryIndex = -1;
        private int _selectedArticleIndex = -1;
        private int _selectedPhotoGalleryIndex = -1;
        private string _selectedPhotoCategory = string.Empty;
        private int _selectedVideoGalleryIndex = -1;
        private string _selectedVideoCategory = string.Empty;

        private int _selectedArticleIndexAccordion = -1;//Accordion Index

        private string _xmlFeed = String.Empty;
        private string _xmlPhotoFeed = String.Empty;
        private string _xmlVideoFeed = String.Empty;
        private bool _isDataOld = false;
        private LibManager _libManager = new LibManager();
        private SearchManager _searchManager = new SearchManager();

        //Settings
        private int _updateFrequency = Settings.Default.ContentUpdateFrequency;

        private DispatcherTimer _timerApplicationLife = new DispatcherTimer();
        private int _applicationLifeDoubleMinutes = 1;
        private string _appID = String.Empty;
        //private string _preferenceCity = "";
        //private string _defaultView = "";

        #region View Settings
        private Dictionary<ViewType, ElementFlowSettings> _viewTypeSectionSettings = new Dictionary<ViewType, ElementFlowSettings>()
        {
            {ViewType.CoverFlow,new ElementFlowSettings() { View = ViewType.CoverFlow, ShowScrollbar = false, ItemGap = 0.35, PopoutDistance = 1.8, FrontItemGap = 0.75, TiltAngle = 60, InitialSelection = ItemSelectionMode.CenterItem,
                EntryPoint = new Vector3D(0,0,0),
                ExitPoint = new Vector3D(0,0,0),
                ElementWidth = 370, ElementHeight = 283,
                Camera = new PerspectiveCamera(){FieldOfView = 60,Position = new Point3D(0, 0.5, 5),LookDirection = new Vector3D(0,-0.5,-5),UpDirection = new Vector3D(0,1,0)} }},

            {ViewType.Tile,new ElementFlowSettings() { View = ViewType.Tile, ShowScrollbar = false, ItemGap = 0.09, PopoutDistance = .5,InitialSelection = ItemSelectionMode.Default, 
                EntryPoint = new Vector3D(0,0,0),
                ExitPoint = new Vector3D(0,0,0),
                ElementWidth = 307, ElementHeight = 283 ,Columns=4,Rows=3,
                Camera = new PerspectiveCamera(){FieldOfView = 45,Position = new Point3D(0, 0, 6.25),LookDirection = new Vector3D(0, 0, -2),UpDirection = new Vector3D(0, 1, 0)}}},

            {ViewType.Tile3D,new ElementFlowSettings() { View = ViewType.Tile3D, ShowScrollbar = false, ItemGap = 0.2,PopoutDistance = 0.75, TiltAngle = 45, InitialSelection = ItemSelectionMode.Default,FrontItemGap=-0.25,
                EntryPoint = new Vector3D(0,0,0),
                ExitPoint = new Vector3D(0,0,0),
                ElementWidth = 307, ElementHeight = 283,Columns=3, 
                Camera = new PerspectiveCamera(){FieldOfView = 45,Position = new Point3D(0, 0, 5),LookDirection = new Vector3D(0, 0, -2),UpDirection = new Vector3D(0, 1, 0)} }}            


        };

        private Dictionary<ViewType, ElementFlowSettings> _viewTypeArticlesListSettings = new Dictionary<ViewType, ElementFlowSettings>()
        {
            {ViewType.CoverFlow,new ElementFlowSettings() { View = ViewType.CoverFlow, ShowScrollbar = false, ItemGap = 0.35, PopoutDistance = 1.8, FrontItemGap = 0.75, TiltAngle = 60, InitialSelection = ItemSelectionMode.CenterItem,
                EntryPoint = new Vector3D(0,0,0),
                ExitPoint = new Vector3D(0,0,0),
                ElementWidth = 370, ElementHeight = 283,
                Camera = new PerspectiveCamera(){FieldOfView = 60,Position = new Point3D(0, 0.5, 5),LookDirection = new Vector3D(0,-0.5,-5),UpDirection = new Vector3D(0,1,0)} }},

            
            {ViewType.Tile,new ElementFlowSettings() { View = ViewType.Tile, ShowScrollbar = true, ItemGap = 0.1, PopoutDistance = 0.5, InitialSelection = ItemSelectionMode.Default, 
                EntryPoint = new Vector3D(0, 0, 0), ExitPoint = new Vector3D(0, 0, 0), 
                ElementWidth = 370, ElementHeight = 280 ,Columns=3,Rows=3, Camera = new PerspectiveCamera(){FieldOfView = 45,Position = new Point3D(0, 0, 6),LookDirection = new Vector3D(0, 0, -6),UpDirection = new Vector3D(0, 1, 0)}}},
            
            {ViewType.Tile3D,new ElementFlowSettings() { View = ViewType.Tile3D, ShowScrollbar = true, ItemGap = 0.4,  PopoutDistance = 0.5,TiltAngle = 45,FrontItemGap=-0.5,
                EntryPoint = new Vector3D(0, 0, 0), InitialSelection = ItemSelectionMode.Default, ExitPoint = new Vector3D(0,0, 0), 
                ElementWidth = 370, ElementHeight = 280, Camera = new PerspectiveCamera(){FieldOfView = 45,Position = new Point3D(0, 0, 6),LookDirection = new Vector3D(0, 0, -2),UpDirection = new Vector3D(0, 1, 0)} }}
        };
        #endregion

        #endregion

        #region Public Properties
        public ObservableCollection<NewsSection> ListDetailedSections {
            get { return (ObservableCollection<NewsSection>)GetValue(ListDetailedSectionsProperty); }
            set { SetValue(ListDetailedSectionsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ListDetailedSections.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ListDetailedSectionsProperty =
            DependencyProperty.Register("ListDetailedSections", typeof(ObservableCollection<NewsSection>), typeof(EditionWindow));

        public ObservableCollection<NewsSection> ListOverviewSections {
            get { return (ObservableCollection<NewsSection>)GetValue(ListOverviewSectionsProperty); }
            set { SetValue(ListOverviewSectionsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ListOverviewSections.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ListOverviewSectionsProperty =
            DependencyProperty.Register("ListOverviewSections", typeof(ObservableCollection<NewsSection>), typeof(EditionWindow));

        public IEnumerable ListMainView {
            get { return (IEnumerable)GetValue(ListMainViewProperty); }
            set { SetValue(ListMainViewProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ListMainView.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ListMainViewProperty =
            DependencyProperty.Register("ListMainView", typeof(IEnumerable), typeof(EditionWindow));

        public ObservableCollection<NewsArticle> ListSelectedSectionArticles {
            get { return (ObservableCollection<NewsArticle>)GetValue(ListSelectedSectionArticlesProperty); }
            set { SetValue(ListSelectedSectionArticlesProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ListSelectedSectionArticles.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ListSelectedSectionArticlesProperty =
            DependencyProperty.Register("ListSelectedSectionArticles", typeof(ObservableCollection<NewsArticle>), typeof(EditionWindow));

        public ObservableCollection<NewsArticle> ListSelectedSectionArticlesAccordion {
            get { return (ObservableCollection<NewsArticle>)GetValue(ListSelectedSectionArticlesAccordionProperty); }
            set { SetValue(ListSelectedSectionArticlesAccordionProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ListSelectedSectionArticles.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ListSelectedSectionArticlesAccordionProperty =
            DependencyProperty.Register("ListSelectedSectionArticlesAccordion", typeof(ObservableCollection<NewsArticle>), typeof(EditionWindow));


        #endregion

        #region Delegates
        public delegate void ArticleSelectedEventHandler(object sender, NewsArticle parameters);
        #endregion

        #region Constructor
        public EditionWindow(string title, string xmlFeed, string xmlPhotoFeed, string xmlVideoFeed, bool isDataOld, string appID) {
            InitializeComponent();
            this.Title = String.Format("{0} : {1}","Quibbler", "Universal News Reader");
            _xmlFeed = xmlFeed;
            _xmlPhotoFeed = xmlPhotoFeed;
            _xmlVideoFeed = xmlVideoFeed;
            _isDataOld = isDataOld;
            _appID = appID;
            try {
                //Check From File
                string filePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"UNRV\timer.txt");
                if (File.Exists(filePath)) {
                    //Read From File
                    StreamReader streamReader = File.OpenText(filePath);
                    string entry = streamReader.ReadLine();
                    if (!String.IsNullOrEmpty(entry)) _applicationLifeDoubleMinutes = Int16.Parse(entry);
                    streamReader.Close();
                    File.Delete(filePath);
                }
            } catch { }
            _timerApplicationLife.Interval = TimeSpan.FromMinutes(0.5);
            _timerApplicationLife.Tick += new EventHandler(_TimerApplicationLifeTick);
            _timerApplicationLife.Start();
            Loaded += new RoutedEventHandler(_MainApplication_Loaded);
            this.Closed += new EventHandler(_ExitApplication);
        }


        #endregion

        #region Handlers

        #region Loaded
        void _MainApplication_Loaded(object sender, RoutedEventArgs e) {
            Debug.WriteLine(string.Format("{0}: EditionWindow Loaded: Starting", DateTime.Now));

            txtVersion.Text = Utilities.GetCurrentVersion();
            txtMsgText.Text = "Loading...";
            message.Visibility = Visibility.Visible;

            _loadInitiaterTimer.Interval = TimeSpan.FromMilliseconds(500);
            _loadInitiaterTimer.Tick += new EventHandler(_loadInitiaterTimer_Tick);
            _loadInitiaterTimer.Start();

            Debug.WriteLine(string.Format("{0}: EditionWindow Loaded: End", DateTime.Now));
        }
        #endregion

        #region Delayed Loading
        void _loadInitiaterTimer_Tick(object sender, EventArgs e) {
            _loadInitiaterTimer.Stop();

            this.ListDetailedSections = new ObservableCollection<NewsSection>();
            this.ListOverviewSections = new ObservableCollection<NewsSection>();
            this.ListSelectedSectionArticles = new ObservableCollection<NewsArticle>();

            Debug.WriteLine(string.Format("{0}: _GetParsedFeed: Starting", DateTime.Now));
            _GetParsedFeed();
            Debug.WriteLine(string.Format("{0}: _GetParsedFeed: Completed", DateTime.Now));
            //Wire Events

            //Close of article gallery
            articleGalleryControl.Close += _CloseArticleEventHandler;
            articleGalleryControl.SelectionChanged += new ArticleGalleryControl.ArticleSelectionChangedEventHandler(_ArticleGalleryControlSelectionChanged);

            //Content List Control
            contentListControl.SelectionClicked += _ContentListControl_SelectionClicked;
            States.Add(ViewWindow.Sections);

            //Header Content List Control
            headerContentListControl.SelectionChanged += _HeaderContentListControl_SelectionChanged;
            /// NOTE: Disabling feature: User can click on the center item to go back to home page.
            headerContentListControl.SelectionClicked += _HeaderContentListControl_SelectionClicked;

            //Tool Bar Control
            toolbarControl.HomeClick += _HomeClick;
            toolbarControl.LiveShareClick += _LiveShareClick;
            toolbarControl.CommentClick += _CommentClick;
            toolbarControl.FeedbackClick += _FeedbackClick;
            toolbarControl.CoverFlowClick += _CoverFlowClick;
            toolbarControl.TileClick += _TileClick;
            toolbarControl.Tile3DClick += _Tile3DClick;
            toolbarControl.SearchClick += new ToolbarControl.SearchClickedEventHandler(_SearchClick);
            toolbarControl.SpiderClick += _SpiderClick;
            toolbarControl.ZoomLevelChanged += new ToolbarControl.ZoomLevelChangedEventHandler(_ArticleZoomLevelChanged);
            toolbarControl.StartScribble += new EventHandler(_StartScribble);
            toolbarControl.EndScribble += new EventHandler(_EndScribble);
            toolbarControl.StartReadOutLoud += new EventHandler(_StartReadOutLoud);
            toolbarControl.EndReadOutLoud += new EventHandler(_EndReadOutLoud);
            toolbarControl.HideBar += new EventHandler(_HideToolbarControl);

            //Spider Events
            spiderControl.Click += new SpiderControl.SpiderArticleClickedEventHandler(_SpiderControlArticleClicked);
            spiderControl.Closed += _SpiderClick;

            //Photo Gallery Control
            photoGalleryControl.Close += new EventHandler(_PhotoGalleryControlClosed);
            photoGalleryControl.SelectionChanged += new PhotoGalleryControl.PhotoSelectionChangedEventHandler(_PhotoGalleryControlSelectionChanged);

            //Sub Category Control
            subCategoryControl.SelectionChanged += new SubCategoryControl.CategorySelectionEventHandler(_SubCategorySelectionChanged);

            //Accordion Control
            accordionControl.DetailsItemsRequired += new EventHandler<AccorionItemSelectedEventArgs>(_AccordionControlDetailsItemsRequired);
            accordionControl.DetailsItemSelected += new EventHandler<AccorionItemSelectedEventArgs>(_AccordionControlDetailsItemSelected);

            //Miscellenous Controls
            lblTimesTitleSmall.MouseLeftButtonUp += _GoHome; // Clicking Times title takes to Home screen

            //Show/Hide Toolbar 
            btnShowToolbarBar.Click += _ShowToolbarBar;
            btnShowToolbarBar.MouseEnter += _ShowToolbarBar;
            (this.Resources["sbShowToolbarControl"] as Storyboard).Completed += new EventHandler(_ShowToolbarControlAnimationCompleted);
            (this.Resources["sbHideToolbarControl"] as Storyboard).Completed += new EventHandler(_HideToolbarControlAnimationCompleted);

            //Ads Control
            adsControlBottom.OfflineUrl = "pack://application:,,/Quibbler - Universal News Reader;component/Images/ads_first.png";
            adsControlBottom.ImageUrl = System.Configuration.ConfigurationManager.AppSettings["AdUrl1"];
            adsControlTop.OfflineUrl = "pack://application:,,/Quibbler - Universal News Reader;component/Images/ads_second.png";
            adsControlTop.ImageUrl = System.Configuration.ConfigurationManager.AppSettings["AdUrl2"];

            //Settings Toolbar
            settingsToolbar.ClickSettings += new EventHandler(_SettingsClicked);
            settingsToolbar.ClickThemes += new EventHandler(_ThemesClicked);

            //Settings Control
            settingsControl.SettingsChanged += new EventHandler(_SettingsChanged);

            //Load Cities
            //_GetListCitiesAvailable();    <- Duplicate code

            //Default View
            _lastSectionViewType = settingsControl.View;
            contentListControl.Settings = _viewTypeSectionSettings[_lastSectionViewType];
            toolbarControl.SetSectionSettings(_lastSectionViewType);

            //Library Manager
            _libManager.DownloadNewsDataComplete += new DownloadDataCompleteHandler(LibManagerDownloadNewsDataCompleted);
            _libManager.DownloadPhotoFeedComplete += new DownloadDataCompleteHandler(LibManagerDownloadPhotoFeedCompleted);
            _libManager.DownloadVideoFeedComplete += new DownloadDataCompleteHandler(LibManagerDownloadVideoFeedComplete);
            _libManager.DownloadNewsProgressChange += new System.ComponentModel.ProgressChangedEventHandler(_libManager_DownloadNewsProgressChange);
            _libManager.DownloadPhotoProgressChange += new System.ComponentModel.ProgressChangedEventHandler(_libManager_DownloadPhotoProgressChange);
            _libManager.DownloadVideoProgressChange += new System.ComponentModel.ProgressChangedEventHandler(_libManager_DownloadVideoProgressChange);

            _lastUpdateTimer.Interval = TimeSpan.FromMinutes(1);
            _lastUpdateTimer.Tick += delegate(object s, EventArgs args) {
                if (!_isUpdateInProgress) {
                    _lastUpdateTime++;
                    settingsToolbar.UpdateTime = (_lastUpdateTime > 1) ? " UPDATED : " + _lastUpdateTime.ToString() + " Mins ago" : " UPDATED : " + _lastUpdateTime.ToString() + " Min ago";
                }
            };

            _updateTimer.Interval = TimeSpan.FromMinutes(_updateFrequency);
            _updateTimer.Tick += delegate(object s, EventArgs args) {
                if (!_isUpdateInProgress) {
                    _UpdateNow();
                }
            };

            Debug.WriteLine(string.Format("{0}: Content update: Starting", DateTime.Now));
            if (_isDataOld) {
                // Initiates content download immediatly (with very short delay)
                // NOTE: _updateTimer.Interval will be reset to user-defined "_updateFrequency" on completion
                _updateTimer.Interval = TimeSpan.FromMilliseconds(2000);
                _updateTimer.Start();
            } else {
                settingsToolbar.UpdateTime = " UPDATED : Just Now";
                settingsToolbar.IsOnline = _isOnline = true;
                _updateTimer.Start();
                _lastUpdateTimer.Start();
            }

            Debug.WriteLine(string.Format("{0}: Content update: Completed", DateTime.Now));
            message.Visibility = Visibility.Collapsed;
        }
        #endregion

        #region Application Life Timer
        void _TimerApplicationLifeTick(object sender, EventArgs e) {
            _applicationLifeDoubleMinutes++;
        }
        #endregion

        #region Accordion Control Events
        void _AccordionControlDetailsItemsRequired(object sender, AccorionItemSelectedEventArgs e) {
            _listArticlesinAccordion.Clear();
            int counter = 0;
            foreach (NewsArticle newsArticle in _GetNewsArticlesByCategory(_mappedAccordionCategories[e.DataItem as string])) {
                //Add only 10 items to the accordion
                if (counter >= 10)
                    break;
                else
                    counter++;
                _listArticlesinAccordion.Add(newsArticle);
            }
            accordionControl.DetailsItemsSource = _listArticlesinAccordion.ToArray();
        }

        void _AccordionControlDetailsItemSelected(object sender, AccorionItemSelectedEventArgs e) {
            lblSpiderMode.Visibility = Visibility.Collapsed;
            spiderControl.Visibility = Visibility.Collapsed;

            if (_isSearchModeOn) {
                _isSearchModeOn = false;
                lblSpiderMode.Visibility = Visibility.Collapsed;
                while (States.Current == ViewWindow.SpiderSearch || States.Current == ViewWindow.ArticleGallerySearch)
                    States.RemoveCurrent();
                while (States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.ArticleGalleryRelated)
                    States.RemoveCurrent();
                while (States.Current == ViewWindow.SpiderPhotoRelated || States.Current == ViewWindow.PhotoGalleryRelated)
                    States.RemoveCurrent();

                lblSpiderMode.Visibility = Visibility.Collapsed;
                articleGalleryControl.Visibility = Visibility.Collapsed;
                spiderControl.Visibility = Visibility.Collapsed;
            }

            if (this.ListSelectedSectionArticlesAccordion != null)
                this.ListSelectedSectionArticlesAccordion.Clear();
            else
                this.ListSelectedSectionArticlesAccordion = new ObservableCollection<NewsArticle>();

            foreach (NewsArticle newsArticle in _listArticlesinAccordion) {
                this.ListSelectedSectionArticlesAccordion.Add(newsArticle);
            }

            //_selectedArticleIndex = this.ListSelectedSectionArticles.IndexOf(e.DataItem as NewsArticle);
            _selectedArticleIndexAccordion = this.ListSelectedSectionArticlesAccordion.IndexOf(e.DataItem as NewsArticle);
            //Open Article in  Article Gallery

            switch (States.Current) {
                case ViewWindow.ArticleGallery: _ShowArticleGalleryWithLastSelectedArticlesAccordion();
                    return;
                case ViewWindow.PhotoGallery: photoGalleryControl.Visibility = Visibility.Collapsed;
                    break;
                case ViewWindow.VideoGallery:
                case ViewWindow.Sections:
                case ViewWindow.ArticlesList:
                    contentListControl.Visibility = Visibility.Hidden;
                    break;
            }

            if (States.Current != ViewWindow.Sections) {
                _ShowHeaderControl_AccordionSubCategoryControl(false);
            }

            States.Add(ViewWindow.ArticleGallery);

            toolbarControl.SetArticleGallerySettings();
            //Order to be maintained
            _ShowArticleGalleryWithLastSelectedArticlesAccordion();
        }
        #endregion

        #region Article Gallery Events
        void _CloseArticleEventHandler(object sender, EventArgs e) {
            if (_isSearchModeOn) {
                _isSearchModeOn = false;
                lblSpiderMode.Visibility = Visibility.Collapsed;
                while (States.Current == ViewWindow.SpiderSearch || States.Current == ViewWindow.ArticleGallerySearch)
                    States.RemoveCurrent();
                while (States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.ArticleGalleryRelated)
                    States.RemoveCurrent();
                while (States.Current == ViewWindow.SpiderPhotoRelated || States.Current == ViewWindow.PhotoGalleryRelated)
                    States.RemoveCurrent();

                if (States.Current == ViewWindow.ArticleGallery) {
                    _ShowArticleGalleryWithLastSelectedArticles();
                    _ShowHeaderControl_SubCategoryControl(true);
                    _EnableHeaderControl_SubCategoryControl(true);
                } else {
                    if (States.Current == ViewWindow.Sections || States.Current == ViewWindow.ArticlesList) {
                        contentListControl.Visibility = Visibility.Visible;
                        if (States.Current == ViewWindow.Sections)
                            toolbarControl.SetSectionSettings(_lastSectionViewType);
                        else
                            toolbarControl.SetArticlesListSettings(_lastArticlesListViewType);
                    } else if (States.Current == ViewWindow.PhotoGallery) {
                        photoGalleryControl.Visibility = Visibility.Visible;
                        toolbarControl.SetPhotoGallerySettings();
                    }
                    articleGalleryControl.Visibility = Visibility.Collapsed;
                    _ShowHeaderControl_SubCategoryControl(true);
                    _EnableHeaderControl_SubCategoryControl(true);
                    if (_isUnavailabilityShown) {
                        lblNoNews.Visibility = Visibility.Visible;
                        toolbarControl.SetDisableAllExceptSearchSettings();
                    }
                }
            } else {
                lblSpiderMode.Visibility = Visibility.Collapsed;
                if (States.Current == ViewWindow.ArticleGalleryRelated) {
                    while (States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.ArticleGalleryRelated)
                        States.RemoveCurrent();
                    if (States.Current == ViewWindow.ArticleGallery) {
                        if (_selectedCategoryIndex == -1)
                            _ShowArticleGalleryWithLastSelectedArticlesAccordion();
                        else
                            _ShowArticleGalleryWithLastSelectedArticles();
                        _ShowHeaderControl_SubCategoryControl(true);
                        _EnableHeaderControl_SubCategoryControl(true);
                    }
                } else if (States.Current == ViewWindow.ArticleGallery) {
                    do {
                        States.RemoveCurrent();         // Ignore rest of the states
                    } while (States.Current != ViewWindow.Sections && States.Current != ViewWindow.ArticlesList
                        && States.Current != ViewWindow.PhotoGallery && States.Current != ViewWindow.None && States.Current != ViewWindow.VideoGallery);

                    if (States.Current == ViewWindow.Sections || States.Current == ViewWindow.ArticlesList || States.Current == ViewWindow.VideoGallery) {
                        contentListControl.Visibility = Visibility.Visible;
                        if (States.Current == ViewWindow.Sections)
                            toolbarControl.SetSectionSettings(_lastSectionViewType);
                        else
                            toolbarControl.SetArticlesListSettings(_lastArticlesListViewType);
                    } else if (States.Current == ViewWindow.PhotoGallery) {
                        photoGalleryControl.Visibility = Visibility.Visible;
                        toolbarControl.SetPhotoGallerySettings();
                    }
                    articleGalleryControl.Visibility = Visibility.Collapsed;
                    _ShowHeaderControl_SubCategoryControl(true);
                    _EnableHeaderControl_SubCategoryControl(true);
                }
            }
        }

        void _ArticleGalleryControlSelectionChanged(object sender, int index) {
            articleGalleryControl.StopSpeaking();
            toolbarControl.ToggleReadAloudFalse();
            if (States.Current == ViewWindow.ArticleGallery) {
                _selectedArticleIndex = index;
            }
        }
        #endregion

        #region Photo Gallery Control
        void _PhotoGalleryControlClosed(object sender, EventArgs e) {
            while (States.Current == ViewWindow.SpiderPhotoRelated || States.Current == ViewWindow.PhotoGalleryRelated)
                States.RemoveCurrent();

            photoGalleryControl.ItemSource = _listCurrentPhotoGalleryArticles;
            photoGalleryControl.SelectedIndex = _selectedPhotoGalleryIndex;
            photoGalleryControl.Visibility = Visibility.Visible;
            photoGalleryControl.ShowClose = false;
            toolbarControl.SetPhotoGallerySettings();
            _ShowHeaderControl_SubCategoryControl(true);
            _EnableHeaderControl_SubCategoryControl(true);
            lblSpiderMode.Visibility = Visibility.Collapsed;
            if (_isUnavailabilityShown) {
                lblNoNews.Visibility = Visibility.Visible;
                toolbarControl.SetDisableAllExceptSearchSettings();
            }
        }

        void _PhotoGalleryControlSelectionChanged(object sender, int index) {
            if (States.Current == ViewWindow.PhotoGallery) {
                _selectedPhotoGalleryIndex = index;
            }
        }
        #endregion

        #region Application Closed
        private void _ExitApplication(object sender, EventArgs e) {
            _timerApplicationLife.Stop();
            try {
                try {
                    CustomWebClient client = new CustomWebClient();
                    client.SetTimeout(3 * 1000);
                    client.DownloadData(new Uri(String.Format("{0}{1}", System.Configuration.ConfigurationSettings.AppSettings["UsageUrl"], String.Format("{0}/{1}/{2}/null", _appID, DateTime.Now.ToString("dd-MM-yyyy"), (_applicationLifeDoubleMinutes * 30).ToString()))));
                } catch {
                    string filePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"UNRV\timer.txt");
                    //Write to File
                    StreamWriter streamWriter = File.CreateText(filePath);
                    streamWriter.WriteLine(_applicationLifeDoubleMinutes.ToString());
                    streamWriter.Close();
                }
            } catch { }

            Application.Current.Shutdown();
        }
        #endregion

        #region Spider & Search
        void _SpiderControlArticleClicked(object sender, SpiderEventArgs eventArgs) {
            if (spiderControl.CurrentMode == SpiderMode.PhotoGallery) {
                if (States.Current == ViewWindow.SpiderPhotoRelated) {
                    States.Add(ViewWindow.PhotoGalleryRelated);
                }
                photoGalleryControl.ItemSource = eventArgs.ItemSource;
                photoGalleryControl.SelectedIndex = eventArgs.ItemSource.IndexOf(eventArgs.SelectedArticle);
                photoGalleryControl.Visibility = Visibility.Visible;
                photoGalleryControl.ShowClose = true;
                toolbarControl.SetPhotoGallerySettings();
                spiderControl.Visibility = Visibility.Collapsed;
            } else {
                if (_isSearchModeOn) {
                    if (States.Current == ViewWindow.SpiderSearch) {
                        States.Add(ViewWindow.ArticleGallerySearch);
                    }
                } else {
                    if (States.Current == ViewWindow.SpiderRelated) {
                        States.Add(ViewWindow.ArticleGalleryRelated);
                    }
                }
                articleGalleryControl.ItemSource = eventArgs.ItemSource;
                articleGalleryControl.SelectedIndex = eventArgs.ItemSource.IndexOf(eventArgs.SelectedArticle);
                articleGalleryControl.Visibility = Visibility.Visible;
                toolbarControl.SetArticleGallerySettings();
                if (_isSearchModeOn) {
                    toolbarControl.SetSpiderToolTip("Show Search Results (Spider view)");
                }
                spiderControl.Visibility = Visibility.Collapsed;
            }
        }

        void _SpiderClick(object sender, EventArgs e) {
            if (spiderControl.Visibility == Visibility.Visible) //Revert to previous View  Window
            {
                spiderControl.Visibility = Visibility.Collapsed;
                lblSpiderMode.Visibility = Visibility.Collapsed;
                if (_isSearchModeOn) {
                    _isSearchModeOn = false;
                    while (States.Current == ViewWindow.SpiderSearch || States.Current == ViewWindow.ArticleGallerySearch)
                        States.RemoveCurrent();
                    while (States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.ArticleGalleryRelated)
                        States.RemoveCurrent();
                    while (States.Current == ViewWindow.SpiderPhotoRelated || States.Current == ViewWindow.PhotoGalleryRelated)
                        States.RemoveCurrent();

                    if (States.Current == ViewWindow.ArticleGallery) {
                        if (_selectedCategoryIndex == -1) {
                            _ShowArticleGalleryAccordion(_selectedArticleIndexAccordion);
                            lblSpiderMode.Visibility = Visibility.Collapsed;
                        } else {
                            _ShowArticleGalleryWithLastSelectedArticles();
                            _ShowHeaderControl_SubCategoryControl(true);
                            _EnableHeaderControl_SubCategoryControl(true);
                            lblSpiderMode.Visibility = Visibility.Collapsed;
                        }
                    } else {
                        if (States.Current == ViewWindow.Sections || States.Current == ViewWindow.ArticlesList) {
                            contentListControl.Visibility = Visibility.Visible;
                            if (States.Current == ViewWindow.Sections)
                                toolbarControl.SetSectionSettings(_lastSectionViewType);
                            else
                                toolbarControl.SetArticlesListSettings(_lastArticlesListViewType);
                        } else if (States.Current == ViewWindow.PhotoGallery) {
                            photoGalleryControl.Visibility = Visibility.Visible;
                            toolbarControl.SetPhotoGallerySettings();
                        } else if (States.Current == ViewWindow.VideoGallery) {
                            contentListControl.Visibility = Visibility.Visible;
                            toolbarControl.SetVideoGallerySettings();
                        }
                        articleGalleryControl.Visibility = Visibility.Collapsed;
                        _ShowHeaderControl_SubCategoryControl(true);
                        _EnableHeaderControl_SubCategoryControl(true);
                    }
                } else //Related
                {
                    if (States.Current == ViewWindow.ArticleGallery) {
                        if (_selectedCategoryIndex == -1)
                            _ShowArticleGalleryWithLastSelectedArticlesAccordion();
                        else
                            _ShowArticleGalleryWithLastSelectedArticles();
                        _ShowHeaderControl_SubCategoryControl(true);
                        _EnableHeaderControl_SubCategoryControl(true);

                    } else if (States.Current == ViewWindow.SpiderPhotoRelated || States.Current == ViewWindow.PhotoGalleryRelated) {
                        while (States.Current == ViewWindow.SpiderPhotoRelated || States.Current == ViewWindow.PhotoGalleryRelated)
                            States.RemoveCurrent();

                        photoGalleryControl.ItemSource = _listCurrentPhotoGalleryArticles;
                        photoGalleryControl.SelectedIndex = _selectedPhotoGalleryIndex;
                        photoGalleryControl.Visibility = Visibility.Visible;
                        photoGalleryControl.ShowClose = false;
                        toolbarControl.SetPhotoGallerySettings();
                        //Show header and subcategory
                        _ShowHeaderControl_SubCategoryControl(true);
                        _EnableHeaderControl_SubCategoryControl(true);
                    } else if (States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.ArticleGalleryRelated) {
                        while (States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.ArticleGalleryRelated)
                            States.RemoveCurrent();
                        if (_selectedCategoryIndex == -1)
                            _ShowArticleGalleryWithLastSelectedArticlesAccordion();
                        else
                            _ShowArticleGalleryWithLastSelectedArticles();
                        _ShowHeaderControl_SubCategoryControl(true);
                        _EnableHeaderControl_SubCategoryControl(true);
                    }
                }
                if (_isUnavailabilityShown) {
                    lblNoNews.Visibility = Visibility.Visible;
                    toolbarControl.SetDisableAllExceptSearchSettings();
                }
            } else //Open Spider
            {
                lblNoNews.Visibility = Visibility.Collapsed;
                if (_isSearchModeOn)  //Search Mode
                {
                    articleGalleryControl.Visibility = Visibility.Collapsed;
                    toolbarControl.SetSpiderToolTip("Hide Search Results");
                } else {
                    try {
                        string category = _listMainCategories[_selectedCategoryIndex];
                        if (category == "Photos")
                            spiderControl.CategoryContext = _selectedPhotoCategory;
                        else
                            spiderControl.CategoryContext = category;
                    } catch { spiderControl.CategoryContext = String.Empty; }

                    if (States.Current == ViewWindow.ArticleGallery) //Article Gallery
                    {
                        if (_isSearchModeOn == false) //Non Search Mode
                        {
                            if (States.Current == ViewWindow.ArticleGallery)
                                States.Add(ViewWindow.SpiderRelated);

                            spiderControl.CurrentMode = SpiderMode.RelatedArticle;
                            spiderControl.CenterArticle = articleGalleryControl.ItemSource[articleGalleryControl.SelectedIndex];
                            articleGalleryControl.Visibility = Visibility.Collapsed;
                            _ShowHeaderControl_SubCategoryControl(false);
                            _EnableHeaderControl_SubCategoryControl(false);
                            headerContentListControl.Visibility = Visibility.Visible;
                            lblSpiderMode.Visibility = Visibility.Visible;
                            lblSpiderModeText.Content = "RELATED ARTICLES";
                            toolbarControl.SetSpiderToolTip("Hide Related Articles");
                        }
                    } else if (States.Current == ViewWindow.ArticleGalleryRelated) {
                        spiderControl.CurrentMode = SpiderMode.RelatedArticle;
                        spiderControl.CenterArticle = articleGalleryControl.ItemSource[articleGalleryControl.SelectedIndex];
                        articleGalleryControl.Visibility = Visibility.Collapsed;
                        spiderControl.Visibility = Visibility.Visible;
                    } else if (States.Current == ViewWindow.PhotoGallery) {
                        if (States.Current == ViewWindow.PhotoGallery)
                            States.Add(ViewWindow.SpiderPhotoRelated);

                        spiderControl.CurrentMode = SpiderMode.PhotoGallery;
                        _ShowHeaderControl_SubCategoryControl(false);
                        _EnableHeaderControl_SubCategoryControl(false);
                        headerContentListControl.Visibility = Visibility.Visible;
                        lblSpiderMode.Visibility = Visibility.Visible;
                        lblSpiderModeText.Content = "RELATED PHOTOS";
                        spiderControl.CenterArticle = photoGalleryControl.ItemSource[photoGalleryControl.SelectedIndex];
                        photoGalleryControl.Visibility = Visibility.Collapsed;
                        toolbarControl.SetSpiderToolTip("Hide Related Photos");
                    }
                    if (States.Current == ViewWindow.PhotoGalleryRelated) {
                        spiderControl.CurrentMode = SpiderMode.PhotoGallery;
                        spiderControl.CenterArticle = photoGalleryControl.ItemSource[photoGalleryControl.SelectedIndex];
                        photoGalleryControl.Visibility = Visibility.Collapsed;
                        spiderControl.Visibility = Visibility.Visible;
                        toolbarControl.SetSpiderToolTip("Hide Related Photos");
                    }
                }
                spiderControl.Visibility = Visibility.Visible;
                toolbarControl.SetSpiderSettings();
            }
        }

        void _SearchClick(object sender, string searchString) {
            if (searchString.Equals("indigoarchitects", StringComparison.OrdinalIgnoreCase) ||
                searchString.Equals("indigo architects", StringComparison.OrdinalIgnoreCase)) {
                _ShowMessage("Quibbler Team",String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}","Amar Palsapure",Environment.NewLine,"Sushil Joshi",Environment.NewLine,"Varun Chopra",Environment.NewLine,"Harshwarshan Joshi",Environment.NewLine,"Rahul Singh"),"pack://application:,,/Quibbler - Universal News Reader;component/Images/Logo-Indigo.png");
                return;
            }
            if (Settings.Default.SearchMode == SearchMode.Online) {
                string url = string.Format(ONLINE_SEARCH_URL, searchString);
                System.Diagnostics.Process.Start(url);
                return;
            }

            _isSearchModeOn = true;
            _searchTerm = searchString.ToUpper();
            lblNoNews.Visibility = Visibility.Collapsed;
            spiderControl.Visibility = Visibility.Collapsed;
            articleGalleryControl.Visibility = Visibility.Collapsed;
            if (States.Current == ViewWindow.ArticlesList) {
                _ShowHeaderControl_SubCategoryControl(false);
                _EnableHeaderControl_SubCategoryControl(false);
                headerContentListControl.Visibility = Visibility.Visible;
                contentListControl.Visibility = Visibility.Collapsed;
            } else if (States.Current == ViewWindow.ArticleGallery) {
                _ShowHeaderControl_SubCategoryControl(false);
                _EnableHeaderControl_SubCategoryControl(false);
                headerContentListControl.Visibility = Visibility.Visible;
                articleGalleryControl.Visibility = Visibility.Collapsed;
            } else if (States.Current == ViewWindow.Sections) {
                contentListControl.Visibility = Visibility.Collapsed;
            } else if (States.Current == ViewWindow.PhotoGallery) {
                _ShowHeaderControl_SubCategoryControl(false);
                _EnableHeaderControl_SubCategoryControl(false);
                headerContentListControl.Visibility = Visibility.Visible;
                photoGalleryControl.Visibility = Visibility.Collapsed;
            } else if (States.Current == ViewWindow.VideoGallery) {
                _ShowHeaderControl_SubCategoryControl(false);
                _EnableHeaderControl_SubCategoryControl(false);
                headerContentListControl.Visibility = Visibility.Visible;
                contentListControl.Visibility = Visibility.Collapsed;
            }

            lblSpiderMode.Visibility = Visibility.Visible;
            lblSpiderModeText.Content = "SEARCH RESULTS FOR :  " + _searchTerm;

            spiderControl.CurrentMode = SpiderMode.Search;
            spiderControl.SearchTerm = _searchTerm;
            spiderControl.Visibility = Visibility.Visible;
            if (States.Current != ViewWindow.SpiderSearch)
                States.Add(ViewWindow.SpiderSearch);
            toolbarControl.SetSpiderSettings();
            toolbarControl.SetSpiderToolTip("Hide Search Results");
        }
        #endregion

        #region Toolbar Control
        void _HomeClick(object sender, EventArgs e) {
            //_ShowMessage("Coming soon...", "Library for managing your news content.", "pack://application:,,/Quibbler - Universal News Reader;component/Images/HoverLibrary.png");
            _GoHome(sender, e);
        }

        void _LiveShareClick(object sender, EventArgs e) {
            _ShowMessage("Coming soon...", "Share your views/opinions with others instantly.", "pack://application:,,/Quibbler - Universal News Reader;component/Images/HoverShare.png");
        }

        void _CommentClick(object sender, EventArgs e) {
            if (_isOnline == false) {
                _ShowMessage("Offline Mode", "You are not Connected to Internet.", "pack://application:,,/Quibbler - Universal News Reader;component/Images/HoverComment.png");
            } else {
                if (States.Current == ViewWindow.ArticleGallery)
                    articleGalleryControl.AddFeedback();
            }
            //_ShowMessage("Coming soon...", "Send an article link to your friend.", "pack://application:,,/Quibbler - Universal News Reader;component/Images/HoverComment.png");
        }

        void _FeedbackClick(object sender, EventArgs e) {
            if (_isOnline == false) {
                _ShowMessage("Offline Mode", "You are not Connected to Internet.", "pack://application:,,/Quibbler - Universal News Reader;component/Images/HoverFeedback.png");
            } else {
                System.Diagnostics.Process.Start(System.Configuration.ConfigurationManager.AppSettings["FeedbackUrl"]);
            }
        }

        void _Tile3DClick(object sender, EventArgs e) {
            if (States.Current == ViewWindow.Sections) {
                _lastSectionViewType = ViewType.Tile3D;
                contentListControl.Settings = _viewTypeSectionSettings[ViewType.Tile3D];
            } else if (States.Current == ViewWindow.ArticlesList || States.Current == ViewWindow.VideoGallery) {
                _lastArticlesListViewType = ViewType.Tile3D;
                contentListControl.Settings = _viewTypeArticlesListSettings[ViewType.Tile3D];
            }
        }

        void _TileClick(object sender, EventArgs e) {
            if (States.Current == ViewWindow.Sections) {
                _lastSectionViewType = ViewType.Tile;
                contentListControl.Settings = _viewTypeSectionSettings[ViewType.Tile];
            } else if (States.Current == ViewWindow.ArticlesList || States.Current == ViewWindow.VideoGallery) {
                _lastArticlesListViewType = ViewType.Tile;
                contentListControl.Settings = _viewTypeArticlesListSettings[ViewType.Tile];
            }
        }

        void _CoverFlowClick(object sender, EventArgs e) {
            if (States.Current == ViewWindow.Sections) {
                _lastSectionViewType = ViewType.CoverFlow;
                contentListControl.Settings = _viewTypeSectionSettings[ViewType.CoverFlow];
            } else if (States.Current == ViewWindow.ArticlesList || States.Current == ViewWindow.VideoGallery) {
                _lastArticlesListViewType = ViewType.CoverFlow;
                contentListControl.Settings = _viewTypeArticlesListSettings[ViewType.CoverFlow];
            }
        }

        void _ArticleZoomLevelChanged(object sender, ZoomLevel zoomLevel) {
            articleGalleryControl.Zoom = zoomLevel;
        }

        void _EndReadOutLoud(object sender, EventArgs e) {
            articleGalleryControl.StopSpeaking();
        }

        void _StartReadOutLoud(object sender, EventArgs e) {
            articleGalleryControl.SpeakAloud();
        }

        void _EndScribble(object sender, EventArgs e) {

        }

        void _StartScribble(object sender, EventArgs e) {
            articleGalleryControl.Scribble();
        }
        #endregion

        #region Content List Clicked
        void _ContentListControl_SelectionClicked(object sender, EventArgs e) {
            if (_isTransitionsOngoing == false) {
                if (States.Current == ViewWindow.Sections) //Selection made on Sections
                {
                    //Add states
                    States.Add(ViewWindow.ArticlesList);
                    //Transitions=true
                    _isTransitionsOngoing = true;
                    _SetTransitionSettingsOn(true);
                    //Hide Masthead
                    _BeginAnimation("sbShowSmallHeading");
                    //Save index
                    _selectedCategoryIndex = contentListControl.SelectedIndex;
                    //Put sections in header
                    headerContentListControl.Visibility = Visibility.Visible;
                    this.ListDetailedSections.Clear();
                    this.ListOverviewSections.Clear();
                    foreach (NewsSection newsSection in _listNewsSections)
                        this.ListOverviewSections.Add(newsSection);
                    headerContentListControl.SelectedIndex = _selectedCategoryIndex;
                    //Hide not required controls
                    //accordionControl.Visibility = Visibility.Collapsed;
                    //adsControlTop.Visibility = Visibility.Visible;
                    //Clear list nd change templates
                    this.ListSelectedSectionArticles.Clear();
                    this.ListMainView = null;
                    this.ListMainView = this.ListSelectedSectionArticles;
                    //contentListControl.ItemTemplate = this.Resources["ArticleDataTemplate"] as DataTemplate;
                    //contentListControl.Settings = _viewTypeArticlesListSettings[_lastArticlesListViewType];
                    //Main Category changed
                    _MainCategorySelectionChanged();
                } else if (States.Current == ViewWindow.ArticlesList) //Selection made on Articles
                {
                    States.Add(ViewWindow.ArticleGallery);
                    contentListControl.Visibility = Visibility.Hidden;
                    _selectedArticleIndex = contentListControl.SelectedIndex;
                    toolbarControl.SetArticleGallerySettings();
                    _ShowArticleGallery(_selectedArticleIndex);
                } else if (States.Current == ViewWindow.VideoGallery) {
                    try {
                        string url = this.ListSelectedSectionArticles[contentListControl.SelectedIndex].VideoUrl;
                        System.Diagnostics.Process.Start(url);
                    } catch (Exception ex) { Utilities.Log("Error launching video: ", ex); }
                }
            }
        }
        #endregion

        #region Header Content List Events
        void _HeaderContentListControl_SelectionClicked(object sender, EventArgs e) {
            if (!_isTransitionsOngoing && headerContentListControl.ItemsSource.Cast<NewsSection>().Count() > 0) {
                if (States.Current == ViewWindow.ArticleGallery || States.Current == ViewWindow.ArticleGallerySearch || States.Current == ViewWindow.ArticleGalleryRelated
                    || States.Current == ViewWindow.SpiderSearch || States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.SpiderPhotoRelated) {
                    _isSearchModeOn = false;
                    spiderControl.Visibility = Visibility.Collapsed;
                    articleGalleryControl.Visibility = Visibility.Collapsed;
                    lblSpiderMode.Visibility = Visibility.Collapsed;
                    States.RemoveCurrent();
                    contentListControl.Visibility = Visibility.Visible;
                }

                _isTransitionsOngoing = true;
                _SetTransitionSettingsOn(true);
                //Save Index
                _selectedCategoryIndex = headerContentListControl.SelectedIndex;
                //Update Articles List
                this.ListSelectedSectionArticles.Clear();
                this.ListSelectedSectionArticles = new ObservableCollection<NewsArticle>();
                this.ListMainView = this.ListSelectedSectionArticles;
                //Main Category Changed
                _MainCategorySelectionChanged();
            }

        }

        void _GoHome(object sender, EventArgs e) {
            if (_isTransitionsOngoing == false && headerContentListControl.ItemsSource.Cast<NewsSection>().Count() > 0) {
                //Transitions=true
                _isTransitionsOngoing = true;
                _SetTransitionSettingsOn(true);

                lblNoNews.Visibility = Visibility.Collapsed;
                if (States.Current == ViewWindow.PhotoGallery) {
                    photoGalleryControl.Visibility = Visibility.Collapsed;
                } else if (States.Current == ViewWindow.ArticleGallery || States.Current == ViewWindow.ArticleGallerySearch || States.Current == ViewWindow.ArticleGalleryRelated
                    || States.Current == ViewWindow.SpiderSearch || States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.SpiderPhotoRelated) {
                    _isSearchModeOn = false;
                    spiderControl.Visibility = Visibility.Collapsed;
                    articleGalleryControl.Visibility = Visibility.Collapsed;
                    lblSpiderMode.Visibility = Visibility.Collapsed;
                    States.RemoveCurrent();
                    contentListControl.Visibility = Visibility.Visible;
                }

                contentListControl.Visibility = Visibility.Visible;
                //Close Articles List
                this.ListSelectedSectionArticles.Clear();
                //Change Templates
                contentListControl.ItemTemplate = null;
                contentListControl.ItemTemplate = this.Resources["NewsFolderDataTemplate"] as DataTemplate;
                //Hide Subcategory Control
                subCategoryControl.ItemSource = null;
                subCategoryControl.Margin = new Thickness(20, 0, 10, 0);
                subCategoryControl.Height = 0;
                subCategoryControl.Visibility = Visibility.Collapsed;
                //Put Data to content list
                this.ListOverviewSections.Clear();

                _UpdateNewsSections();

                contentListControl.Settings = _viewTypeSectionSettings[_lastSectionViewType];
                //Set Toolbar settings
                toolbarControl.SetSectionSettings(_lastSectionViewType);
                //show masthead and required control
                _BeginAnimation("sbShowLargeHeading");
                headerContentListControl.Visibility = Visibility.Hidden;
                accordionControl.Visibility = Visibility.Visible;
                adsControlTop.Visibility = Visibility.Collapsed;
                contentListControl.Background = null;
                //Reset states
                States.Clear();
                States.Add(ViewWindow.Sections);
                //Transitions=false
                _isTransitionsOngoing = false;
                _SetTransitionSettingsOn(false);
                _selectedCategoryIndex = -1;
            }
        }

        void _HeaderContentListControl_SelectionChanged(object sender, EventArgs e) {
            if (!_isTransitionsOngoing && headerContentListControl.ItemsSource.Cast<NewsSection>().Count() > 0) {
                if (States.Current == ViewWindow.ArticleGallery || States.Current == ViewWindow.ArticleGallerySearch || States.Current == ViewWindow.ArticleGalleryRelated
                    || States.Current == ViewWindow.SpiderSearch || States.Current == ViewWindow.SpiderRelated || States.Current == ViewWindow.SpiderPhotoRelated) {
                    _isSearchModeOn = false;
                    spiderControl.Visibility = Visibility.Collapsed;
                    articleGalleryControl.Visibility = Visibility.Collapsed;
                    lblSpiderMode.Visibility = Visibility.Collapsed;
                    States.RemoveCurrent();
                    contentListControl.Visibility = Visibility.Visible;
                }

                _isTransitionsOngoing = true;
                _SetTransitionSettingsOn(true);
                //Save Index
                _selectedCategoryIndex = headerContentListControl.SelectedIndex;
                //Update Articles List
                this.ListSelectedSectionArticles.Clear();
                this.ListSelectedSectionArticles = new ObservableCollection<NewsArticle>();
                this.ListMainView = this.ListSelectedSectionArticles;
                //Main Category Changed
                _MainCategorySelectionChanged();
            }
        }
        #endregion

        #region Sub Category Selection Changed
        void _SubCategorySelectionChanged(object sender, string category) {
            if (_listMainCategories[_selectedCategoryIndex].ToLower().Equals("photos")) //Photo Gallery
            {
                lblNoNews.Visibility = Visibility.Collapsed;
                _isUnavailabilityShown = false;
                _selectedPhotoGalleryIndex = 0;
                contentListControl.Visibility = Visibility.Hidden;
                photoGalleryControl.Visibility = Visibility.Collapsed;
                _listCurrentPhotoGalleryArticles = _GetSelectedCategoryPhotos(category);
                _selectedPhotoCategory = category;

                if (_listCurrentPhotoGalleryArticles.Count > 0) {
                    photoGalleryControl.ItemSource = _listCurrentPhotoGalleryArticles;
                    photoGalleryControl.SelectedIndex = _selectedPhotoGalleryIndex;
                    photoGalleryControl.Visibility = Visibility.Visible;
                    toolbarControl.SetPhotoGallerySettings();
                } else {
                    this.ListSelectedSectionArticles.Clear();
                    contentListControl.Visibility = Visibility.Visible;
                    photoGalleryControl.ItemSource = null;
                    lblNoNews.Visibility = Visibility.Visible;
                    lblNoNews.Content = "Content not Available";
                    toolbarControl.SetDisableAllExceptSearchSettings();
                    _isUnavailabilityShown = true;
                }
                //Transitions=false
                _isTransitionsOngoing = false;
                _SetTransitionSettingsOn(false);
            } else if (_listMainCategories[_selectedCategoryIndex].ToLower().Equals("videos")) //Video Gallery
            {
                lblNoNews.Visibility = Visibility.Collapsed;
                _isUnavailabilityShown = false;
                this.ListSelectedSectionArticles.Clear();
                this.ListSelectedSectionArticles = new ObservableCollection<NewsArticle>();
                this.ListMainView = this.ListSelectedSectionArticles;

                _AddSelectedCategoryVideos(category);
            } else {
                lblNoNews.Visibility = Visibility.Collapsed;
                _isUnavailabilityShown = false;

                this.ListSelectedSectionArticles.Clear();
                this.ListSelectedSectionArticles = new ObservableCollection<NewsArticle>();
                this.ListMainView = this.ListSelectedSectionArticles;

                string categoryPath = String.Empty;
                if (category.Equals("Top Stories"))
                    categoryPath = _listMainCategories[_selectedCategoryIndex];
                else
                    categoryPath = _listMainCategories[_selectedCategoryIndex] + "/" + category;
                //Get Subcategory Data
                _AddSelectedCategoryArticles(categoryPath);
            }
        }
        #endregion

        #region Lib Manager Download
        void LibManagerDownloadNewsDataCompleted(object sender, DownloadCompleteEventArgs e) {
            try {
                CustomWebClient client = new CustomWebClient();
                client.SetTimeout(3 * 1000);
                client.DownloadData(new Uri(System.Configuration.ConfigurationManager.AppSettings["CategoryUrl"]));
            } catch { e.Cancelled = true; } //TODO:Correct this in Downloader. Added Hack
            if (e.Cancelled) {
                settingsToolbar.IsOnline = _isOnline = false;
                settingsToolbar.UpdateTime = (_lastUpdateTime > 0) ? string.Format(" UPDATED : {0} Mins ago", _lastUpdateTime.ToString()) : string.Empty;
                _isUpdateInProgress = false;
                _updateTimer.Interval = TimeSpan.FromMinutes(1);   // In case of possible connection failure try again every minute
                _updateTimer.Start();
                if (_lastUpdateTime > 0) _lastUpdateTimer.Start(); // Start _lastUpdateTimer only when last successful update time is known 

                if (e.Error != null)
                    Utilities.Log("Content update failed: " + e.Error.Message, Utilities.MessageType.Warning);
            } else {
                Parser.RefreshXmlDoc(ContentType.News, _xmlFeed);
                _libManager.DownloadPhotoFeedAsync(_libManager.GetPublications()[0].Title, null);
            }

        }

        void LibManagerDownloadPhotoFeedCompleted(object sender, DownloadCompleteEventArgs e) {
            Parser.RefreshXmlDoc(ContentType.Photo, _xmlPhotoFeed);
            _libManager.DownloadVideoFeedAsync(_libManager.GetPublications()[0].Title, null);

            if (e.Cancelled && e.Error != null)
                Utilities.Log("Content update failed: " + e.Error.Message, Utilities.MessageType.Warning);
        }

        void LibManagerDownloadVideoFeedComplete(object sender, DownloadCompleteEventArgs e) {
            Parser.RefreshXmlDoc(ContentType.Video, _xmlVideoFeed);

            _isUpdateInProgress = false;
            settingsToolbar.UpdateTime = " UPDATED : Just Now";
            settingsToolbar.FlashStatus();
            _lastUpdateTime = 0;
            _lastUpdateTimer.Start();

            _updateTimer.Interval = TimeSpan.FromMinutes(_updateFrequency);
            _updateTimer.Start();
            _UpdateDataCompleted();

            if (e.Cancelled && e.Error != null)
                Utilities.Log("Content update failed: " + e.Error.Message, Utilities.MessageType.Warning);
        }

        void _libManager_DownloadNewsProgressChange(object sender, ProgressChangedEventArgs e) {
            settingsToolbar.UpdateTime = string.Format(" Updating {0}% ...", (int)(e.ProgressPercentage * 0.5));
        }

        void _libManager_DownloadPhotoProgressChange(object sender, ProgressChangedEventArgs e) {
            settingsToolbar.UpdateTime = string.Format(" Updating {0}% ...", 50 + (int)(e.ProgressPercentage * 0.4));
        }

        void _libManager_DownloadVideoProgressChange(object sender, ProgressChangedEventArgs e) {
            settingsToolbar.UpdateTime = string.Format(" Updating {0}% ...", 75 + (int)(e.ProgressPercentage * 0.1));
        }
        #endregion

        #region Settings Toolbar
        void _SettingsClicked(object sender, EventArgs e) {
            settingsControl.Show();
        }

        void _ThemesClicked(object sender, EventArgs e) {
            _ShowMessage("Coming soon...", "Change your Universal News Reader theme.", "pack://application:,,/Quibbler - Universal News Reader;component/Images/HoverDiwali.png");
        }
        #endregion

        #region Settings Control
        void _SettingsChanged(object sender, EventArgs e) {
            //Update Timer
            if (_updateFrequency != settingsControl.ContentUpdateFrequency) {
                _updateFrequency = settingsControl.ContentUpdateFrequency;
                _updateTimer.Interval = TimeSpan.FromMinutes(_updateFrequency);
                if (!_isUpdateInProgress)
                    _UpdateNow();
            }
        }
        #endregion

        #region Show/Hide Toolbar Control
        void _HideToolbarControl(object sender, EventArgs e) {
            _BeginAnimation("sbHideToolbarControl");
        }

        void _ShowToolbarBar(object sender, EventArgs e) {
            btnShowToolbarBar.Visibility = Visibility.Collapsed;
            toolbarControl.Visibility = Visibility.Visible;
            _BeginAnimation("sbShowToolbarControl");
        }
        void _ShowToolbarControlAnimationCompleted(object sender, EventArgs e) {
        }
        void _HideToolbarControlAnimationCompleted(object sender, EventArgs e) {
            btnShowToolbarBar.Visibility = Visibility.Visible;
            toolbarControl.Visibility = Visibility.Collapsed;
        }
        #endregion

        #endregion

        #region Private Helper Functions

        #region Show Article Gallery With last selected Articles
        private void _ShowArticleGalleryWithLastSelectedArticles() {
            _ShowArticleGallery(_selectedArticleIndex);
        }

        private void _ShowArticleGallery(int selectedArticleIndex) {
            articleGalleryControl.ItemSource = this.ListSelectedSectionArticles.ToList();
            if (this.ListSelectedSectionArticles != null && this.ListSelectedSectionArticles.Count > 0) {
                articleGalleryControl.SelectedIndex = selectedArticleIndex;
                toolbarControl.SetArticleGallerySettings();
            } else {
                toolbarControl.SetDisableAllExceptSearchSettings();
            }
            articleGalleryControl.Visibility = Visibility.Visible;
        }
        #endregion

        #region Show Article Gallery With last selected Articles for Accordion
        private void _ShowArticleGalleryWithLastSelectedArticlesAccordion() {
            _ShowArticleGalleryAccordion(_selectedArticleIndexAccordion);
        }

        private void _ShowArticleGalleryAccordion(int selectedArticleIndex) {
            articleGalleryControl.ItemSource = this.ListSelectedSectionArticlesAccordion.ToList();
            if (this.ListSelectedSectionArticlesAccordion != null && this.ListSelectedSectionArticlesAccordion.Count > 0) {
                articleGalleryControl.SelectedIndex = selectedArticleIndex;
                toolbarControl.SetArticleGallerySettings();
            } else
                toolbarControl.SetDisableAllExceptSearchSettings();
            articleGalleryControl.Visibility = Visibility.Visible;
        }
        #endregion

        #region Show/Hide Enable/Disable Header and Subcategory
        private void _ShowHeaderControl_SubCategoryControl(bool show) {
            if (show) {
                headerContentListControl.Visibility = Visibility.Visible;
                subCategoryControl.Visibility = Visibility.Visible;
            } else {
                headerContentListControl.Visibility = Visibility.Collapsed;
                subCategoryControl.Visibility = Visibility.Collapsed;
            }
        }

        private void _ShowHeaderControl_AccordionSubCategoryControl(bool show) {
            if (show) {
                headerContentListControl.IsHitTestVisible = true;
                subCategoryControl.Visibility = Visibility.Visible;
            } else {
                headerContentListControl.IsHitTestVisible = true;
                subCategoryControl.Visibility = Visibility.Collapsed;

            }
        }

        private void _EnableHeaderControl_SubCategoryControl(bool enable) {
            if (enable) {
                // headerContentListControl.Opacity = 1;
                // headerContentListControl.IsHitTestVisible = true;
                subCategoryControl.Opacity = 1;
                subCategoryControl.IsHitTestVisible = true;
            } else {
                // headerContentListControl.Opacity = 0.7;
                // headerContentListControl.IsHitTestVisible = false;
                subCategoryControl.Opacity = 0.7;
                subCategoryControl.IsHitTestVisible = false;
            }

            /// IMPORTANT: headerContentListControl should be always enabled
            headerContentListControl.IsHitTestVisible = true;
        }
        #endregion

        #region Transition Settings
        private void _SetTransitionSettingsOn(bool transitionSettingsOn) {
            headerContentListControl.IsHitTestVisible = !transitionSettingsOn;
            contentListControl.IsHitTestVisible = !transitionSettingsOn;
            toolbarControl.IsHitTestVisible = !transitionSettingsOn;
            subCategoryControl.IsHitTestVisible = !transitionSettingsOn;
            accordionControl.IsHitTestVisible = !transitionSettingsOn;
        }
        #endregion

        #region Main Category Selection Changed
        private void _MainCategorySelectionChanged() {
            States.RemoveCurrent();
            photoGalleryControl.Visibility = Visibility.Collapsed;
            contentListControl.Visibility = Visibility.Collapsed;

            string category = _listMainCategories[_selectedCategoryIndex];
            if (category.ToLower().Equals("photos")) {
                States.Add(ViewWindow.PhotoGallery);
                photoGalleryControl.Visibility = Visibility.Visible;

                //Get Categories for Photos
                List<string> list = Parser.GetInstance(ContentType.Photo, _xmlPhotoFeed).PhotoCategoryInfo(_xmlPhotoFeed);
                _listSubCategories = new List<string>();
                if (list != null && list.Count > 0) {
                    foreach (string categoryPath in list) {
                        _listSubCategories.Add(categoryPath.Split('/')[0]);
                    }
                }
                if (_listSubCategories != null && _listSubCategories.Count >= 0) {
                    //_listSubCategories.Insert(0, _listMainCategories[_selectedCategoryIndex]);
                    subCategoryControl.ItemSource = null;
                    subCategoryControl.ItemSource = _listSubCategories;
                    subCategoryControl.Margin = new Thickness(20, 5, 10, 5);
                    subCategoryControl.Height = Double.NaN;
                    subCategoryControl.Visibility = Visibility.Visible;
                    subCategoryControl.SelectedIndex = 0;
                } else //If no subcategories Exist
                {
                    subCategoryControl.ItemSource = null;
                    subCategoryControl.Margin = new Thickness(20, 0, 10, 0);
                    subCategoryControl.Height = 0;
                    lblNoNews.Visibility = Visibility.Visible;
                    lblNoNews.Content = "Content not Available";
                    toolbarControl.SetDisableAllExceptSearchSettings();
                    _isUnavailabilityShown = true;
                    //Transitions=false
                    _isTransitionsOngoing = false;
                    _SetTransitionSettingsOn(false);
                }
            } else if (category.ToLower().Equals("videos")) {
                States.Add(ViewWindow.VideoGallery);
                contentListControl.Visibility = Visibility.Visible;

                //Get Categories for Videos
                List<string> list = Parser.GetInstance(ContentType.Video, _xmlVideoFeed).VideoCategoryInfo(_xmlVideoFeed);
                _listSubCategories = new List<string>();
                if (list != null && list.Count > 0) {
                    foreach (string categoryPath in list) {
                        _listSubCategories.Add(categoryPath.Split('/')[0]);
                    }
                }
                if (_listSubCategories != null && _listSubCategories.Count >= 0) {
                    //_listSubCategories.Insert(0, _listMainCategories[_selectedCategoryIndex]);
                    subCategoryControl.ItemSource = null;
                    subCategoryControl.ItemSource = _listSubCategories;
                    subCategoryControl.Margin = new Thickness(20, 5, 10, 5);
                    subCategoryControl.Height = Double.NaN;
                    subCategoryControl.Visibility = Visibility.Visible;
                    subCategoryControl.SelectedIndex = 0;
                } else //If no subcategories Exist
                {
                    subCategoryControl.ItemSource = null;
                    subCategoryControl.Margin = new Thickness(20, 0, 10, 0);
                    subCategoryControl.Height = 0;
                    lblNoNews.Visibility = Visibility.Visible;
                    lblNoNews.Content = "Content not Available";
                    toolbarControl.SetDisableAllExceptSearchSettings();
                    _isUnavailabilityShown = true;
                    //Transitions=false
                    _isTransitionsOngoing = false;
                    _SetTransitionSettingsOn(false);
                }

                #region Old code
                //States.RemoveCurrent();
                //States.Add(ViewWindow.ArticlesList);
                //this.ListSelectedSectionArticles.Clear();
                //contentListControl.Visibility = Visibility.Visible;
                //subCategoryControl.ItemSource = null;
                //subCategoryControl.Margin = new Thickness(20, 0, 10, 0);
                //subCategoryControl.Height = 0;
                //photoGalleryControl.Visibility = Visibility.Collapsed;
                //lblNoNews.Visibility = Visibility.Visible;
                //lblNoNews.Content = "Content not Available";
                //toolbarControl.SetDisableAllExceptSearchSettings();
                //_isUnavailabilityShown = true;
                //if (contentListControl.Background == null)
                //{
                //    contentListControl.Background = new ImageBrush(BitmapDecoder.Create(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/backgroundGlow.png", UriKind.RelativeOrAbsolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default).Frames[0]);
                //}
                ////Transitions=false
                //_isTransitionsOngoing = false;
                //_SetTransitionSettingsOn(false);
                #endregion
            } else //Articles
            {
                States.Add(ViewWindow.ArticlesList);
                contentListControl.Visibility = Visibility.Visible;

                _GetSubCategories();
                _listSubCategories.Insert(0, "Top Stories");
                subCategoryControl.ItemSource = null;
                subCategoryControl.ItemSource = _listSubCategories;
                subCategoryControl.Margin = new Thickness(20, 5, 10, 5);
                subCategoryControl.Height = Double.NaN;
                subCategoryControl.Visibility = Visibility.Visible;
                if (category.ToLower().Equals("city") && !String.IsNullOrEmpty(settingsControl.City)) //For City Open Prefered City
                {
                    if (_listSubCategories.Contains(settingsControl.City))
                        subCategoryControl.SelectedIndex = _listSubCategories.IndexOf(settingsControl.City);
                    else
                        subCategoryControl.SelectedIndex = 0;
                } else
                    subCategoryControl.SelectedIndex = 0;
            }
        }
        #endregion

        #region Get Sub categories data
        private void _GetSubCategories() {
            List<string> list = new List<string>();
            try {
                list = Parser.GetInstance(ContentType.News, _xmlFeed).CategoryInfo(_xmlFeed, _listMainCategories[_selectedCategoryIndex]);
            } catch { }
            _listSubCategories = new List<string>();
            if (list != null && list.Count > 0) {
                foreach (string categoryPath in list) {
                    _listSubCategories.Add(categoryPath.Split('/')[1]);
                }
            }
        }
        #endregion

        #region Get Selected Category Photos / Videos
        private List<NewsArticle> _GetSelectedCategoryPhotos(string photoCategory) {
            try {
                _listCurrentPhotoGalleryArticles = Parser.GetInstance(ContentType.Photo, _xmlPhotoFeed).PhotoArticleList(_xmlPhotoFeed, photoCategory);
            } catch { _listCurrentPhotoGalleryArticles = new List<NewsArticle>(); }
            //Get strings
            List<string> photos = (from photoArticle in _listCurrentPhotoGalleryArticles
                                   select photoArticle.ImageUrl).ToList();
            return _listCurrentPhotoGalleryArticles;
        }

        private List<NewsArticle> _GetSelectedCategoryVideos(string videoCategory) {
            try {
                _listCurrentVideoGalleryArticles = Parser.GetInstance(ContentType.Video, _xmlVideoFeed).VideoArticleList(_xmlVideoFeed, videoCategory);
            } catch { _listCurrentVideoGalleryArticles = new List<NewsArticle>(); }
            //Get strings
            List<string> videos = (from videoArticle in _listCurrentVideoGalleryArticles
                                   select videoArticle.ImageUrl).ToList();
            return _listCurrentVideoGalleryArticles;
        }
        #endregion

        #region Add Selected Category data to view
        private void _AddSelectedCategoryArticles(string categoryPath) {
            _addCategoryTimer.Stop();
            _addCategoryTimer = new DispatcherTimer();
            _addCategoryTimer.Tick += delegate(object s, EventArgs args) {
                _addCategoryTimer.Stop();
                IEnumerable<NewsArticle> tempList = _GetNewsArticlesByCategory(categoryPath);
                lblNoNews.Visibility = Visibility.Collapsed;
                contentListControl.ItemTemplate = null;
                contentListControl.ItemTemplate = this.Resources["ArticleDataTemplate"] as DataTemplate;
                contentListControl.Settings = _viewTypeArticlesListSettings[_lastArticlesListViewType];

                if (tempList.Cast<NewsArticle>().ToList().Count > 0) {
                    foreach (NewsArticle newsArticle in tempList) {
                        this.ListSelectedSectionArticles.Add(newsArticle);
                    }
                    if (_lastArticlesListViewType == ViewType.CoverFlow) //To select the centre item in Coverflow
                    {
                        try { _selectedArticleIndex = (tempList.Cast<NewsArticle>().ToList().Count - 1) / 2; } catch //Default Select -1th item
                        { _selectedArticleIndex = -1; }
                        contentListControl.SelectedIndex = _selectedArticleIndex;
                    }
                } else //if list is empty
                {
                    if (States.Current == ViewWindow.ArticlesList) {
                        lblNoNews.Visibility = Visibility.Visible;
                        lblNoNews.Content = "Content not Available";
                        toolbarControl.SetDisableAllExceptSearchSettings();
                    }
                    _isUnavailabilityShown = true;
                }
                if (States.Current == ViewWindow.ArticleGallery) {
                    _selectedArticleIndex = 0;
                    _ShowArticleGalleryWithLastSelectedArticles();
                } else {
                    if (!_isUnavailabilityShown)
                        toolbarControl.SetArticlesListSettings(_lastArticlesListViewType);
                    //if (contentListControl.Background == null)
                    //{
                    //    contentListControl.Background = new ImageBrush(BitmapDecoder.Create(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/backgroundGlow.png", UriKind.RelativeOrAbsolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default).Frames[0]);
                    //}
                }
                //transitions = false
                _isTransitionsOngoing = false;
                _SetTransitionSettingsOn(false);
            };
            _addCategoryTimer.Interval = TimeSpan.FromSeconds(0.4);
            _addCategoryTimer.Start();
        }

        private void _AddSelectedCategoryVideos(string categoryPath) {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += delegate(object s, EventArgs args) {
                timer.Stop();
                IEnumerable<NewsArticle> tempList = _GetVideosByCategory(categoryPath);
                lblNoNews.Visibility = Visibility.Collapsed;
                contentListControl.ItemTemplate = null;
                //contentListControl.SetResourceReference(
                contentListControl.ItemTemplate = this.Resources["VideoDataTemplate"] as DataTemplate;    // TODO: Change template
                contentListControl.Settings = _viewTypeArticlesListSettings[_lastArticlesListViewType];

                this.ListSelectedSectionArticles.Clear();
                if (tempList.Cast<NewsArticle>().ToList().Count > 0) {
                    foreach (NewsArticle newsArticle in tempList) {
                        this.ListSelectedSectionArticles.Add(newsArticle);
                    }
                    if (_lastArticlesListViewType == ViewType.CoverFlow) //To select the centre item in Coverflow
                    {
                        try { _selectedArticleIndex = (tempList.Cast<NewsArticle>().ToList().Count - 1) / 2; } catch //Default Select -1th item
                        { _selectedArticleIndex = -1; }
                        contentListControl.SelectedIndex = _selectedArticleIndex;
                    }
                } else //if list is empty
                {
                    lblNoNews.Visibility = Visibility.Visible;
                    lblNoNews.Content = "Content not Available";
                    toolbarControl.SetDisableAllExceptSearchSettings();
                    _isUnavailabilityShown = true;
                }

                if (!_isUnavailabilityShown)
                    toolbarControl.SetVideoGallerySettings();
                // toolbarControl.SetDisableAllExceptSearchSettings(); // TODO: Allow switching views: tile/tile3D
                //if (contentListControl.Background == null)
                //    contentListControl.Background = new ImageBrush(BitmapDecoder.Create(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/backgroundGlow.png", UriKind.RelativeOrAbsolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default).Frames[0]);

                //transitions = false
                _isTransitionsOngoing = false;
                _SetTransitionSettingsOn(false);
            };
            timer.Interval = TimeSpan.FromSeconds(0.4);
            timer.Start();
        }
        #endregion

        #region Parse n Get Data Helper Functions
        private void _GetParsedFeed() {
            try {
                #region Accordion Source
                _mappedAccordionCategories.Add("Top Stories", "Home");
                _mappedAccordionCategories.Add("Most Recent News", "Recent News");
                _mappedAccordionCategories.Add("Most Read", "Home/Most Read");
                _mappedAccordionCategories.Add("Most Shared", "Home/Most Shared");
                _mappedAccordionCategories.Add("Most Commented", "Home/Most Commented");
                _mappedAccordionCategories.Add("Bollywood Movie Reviews", "Movie Reviews/Hindi");
                _mappedAccordionCategories.Add("Hollywood Movie Reviews", "Movie Reviews/English");
                _mappedAccordionCategories.Add("Opinion", "Home/Opinion");

                accordionControl.MasterItemsSource = _mappedAccordionCategories.Keys.ToArray();
                #endregion


                _UpdateNewsSections();

                //_listNewsSections.Add(new NewsSection()
                //{
                //    Category = "Videos",
                //    NewsArticles = new List<NewsArticle>()
                //});


                //_listNewsSections.Add(new NewsSection()
                //{
                //    Category = "Photos",
                //    NewsArticles = new List<NewsArticle>()
                //});

                _GetListCitiesAvailable();
            } catch (Exception ex) {
                //MessageBox.Show("Parsing Error:" + ex.Message);
            }
        }

        private void _UpdateNewsSections() {
            //Get Main Categories
            List<Category> categories = new List<Category>();
            //_listMainCategories.Clear();

            try {
                categories = _libManager.GetCategories(_libManager.GetPublications()[0].Title, RSSType.News).ToList();
            } catch { ; }

            if (categories == null || categories.Count == 0) {
                XmlDocument catDoc = new XmlDocument();
                catDoc.LoadXml(Indigo.Quibbler.Properties.Resources.Categories);
                XmlNodeList catNodeList = catDoc.SelectNodes("publication/category");
                foreach (XmlNode catNode in catNodeList) {
                    categories.Add(new Category() {
                        CallbackName = catNode.Attributes["callBackName"].Value,
                        Name = catNode.Attributes["categoryName"].Value
                    });
                }
            }

            foreach (Category cat in categories) {
                string catName = cat.Name.Split('/')[0];
                if (!String.IsNullOrEmpty(catName) && !_listMainCategories.Contains(catName))
                    _listMainCategories.Add(catName);
            }

            if (!_listMainCategories.Contains("Videos")) _listMainCategories.Add("Videos");
            if (!_listMainCategories.Contains("Photos")) _listMainCategories.Add("Photos");

            //Get Main Category Articles
            _listNewsSections = new List<NewsSection>();
            foreach (string mainCategory in _listMainCategories) {
                _listNewsSections.Add(new NewsSection() {
                    Category = mainCategory,
                    NewsArticles = Parser.GetInstance(ContentType.News, _xmlFeed).ArticleList(_xmlFeed, mainCategory)
                });
            }

            // Update datasource
            this.ListDetailedSections.Clear();
            foreach (NewsSection newsSection in _listNewsSections)
                this.ListDetailedSections.Add(newsSection);

            this.ListMainView = null;
            this.ListMainView = this.ListDetailedSections;
        }

        private IEnumerable<NewsArticle> _GetNewsArticlesByCategory(string category) {
            return Parser.GetInstance(ContentType.News, _xmlFeed).ArticleList(_xmlFeed, category);
        }

        private IEnumerable<NewsArticle> _GetVideosByCategory(string category) {
            return Parser.GetInstance(ContentType.Video, _xmlVideoFeed).VideoArticleList(_xmlVideoFeed, category);
        }

        #endregion

        #region Gets & Load List of Cities
        private void _GetListCitiesAvailable() {
            List<string> list = new List<string>();
            try {
                //Get List of Cities Available
                list = Parser.GetInstance(ContentType.News, _xmlFeed).CategoryInfo(_xmlFeed, "City");
            } catch { }
            _listOfCitiesAvailable = new List<string>();
            if (list != null && list.Count > 0) {
                foreach (string categoryPath in list) {
                    _listOfCitiesAvailable.Add(categoryPath.Split('/')[1]);
                }
            }
            settingsControl.CityCollection = _listOfCitiesAvailable;
        }
        #endregion

        #region Content Update
        private void _UpdateDataCompleted() {
            if (States.Current == ViewWindow.Sections) _UpdateNewsSections();

            _GetListCitiesAvailable();
        }

        private void _UpdateNow() {
            _updateTimer.Stop();
            _lastUpdateTimer.Stop();
            settingsToolbar.UpdateTime = " Updating...";
            settingsToolbar.IsOnline = _isOnline = true;
            _isUpdateInProgress = true;
            _libManager.DownloadNewsDataAsync(_libManager.GetPublications()[0].Title, null);
        }
        #endregion

        #region Begin/Stop Animation
        private void _BeginAnimation(string storyboardKey) {
            try {
                Storyboard Animation = this.Resources[storyboardKey] as Storyboard;
                if (Animation != null) {
                    Animation.Begin();
                }
            } catch (Exception ex) { }
        }
        private void _StopAnimation(string storyboardKey) {
            try {
                Storyboard Animation = this.Resources[storyboardKey] as Storyboard;
                if (Animation != null) {
                    Animation.Stop();
                }
            } catch (Exception ex) { }
        }
        #endregion

        #region Miscellenous
        private void _ShowMessage(string message, string description, string iconUrl) {
            txtMsgText.Text = message;
            txtMsgDescription.Text = description;
            txtMsgDescription.Visibility = (string.IsNullOrEmpty(description)) ? Visibility.Collapsed : Visibility.Visible;
            imgMsgIcon.Source = (string.IsNullOrEmpty(iconUrl)) ? null : new BitmapImage(new Uri(iconUrl, UriKind.RelativeOrAbsolute));
            imgMsgIcon.Visibility = (string.IsNullOrEmpty(iconUrl)) ? Visibility.Collapsed : Visibility.Visible;
            (FindResource("sbMessageFlash") as Storyboard).Begin();
        }
        #endregion

        #endregion
    }

    public class States {
        public static ViewWindow Current {
            get { return _listsStates[_listsStates.Count - 1]; }
        }
        private static List<ViewWindow> _listsStates = new List<ViewWindow>() { ViewWindow.None };
        public static void Add(ViewWindow addState) {
            _listsStates.Add(addState);
        }
        public static void RemoveCurrent() {
            if (_listsStates.Count > 1)
                _listsStates.RemoveAt(_listsStates.Count - 1);
        }
        public static void Clear() {
            _listsStates.Clear();
            _listsStates.Add(ViewWindow.None);
        }

        public static ViewWindow GetPrev(int stepsBefore) {
            try {
                ViewWindow state = _listsStates[_listsStates.Count - stepsBefore - 1];
                return state;
            } catch { return ViewWindow.None; }
        }
    }

    #region News Folder Stripped List Coverter
    public class NewsFolderItemsConverter : IValueConverter {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            List<NewsArticle> listArticles = value as List<NewsArticle>;
            if (listArticles.Count >= 3) {
                List<NewsArticle> strippedList = new List<NewsArticle>();
                for (int i = 0; i < 3; i++) {
                    strippedList.Add(listArticles[i]);
                }
                return strippedList;
            }
            return listArticles;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            return value;
        }

        #endregion
    }
    #endregion

    #region Multiplier Converter
    public class MultiplierConverter : IValueConverter {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            return (value != null) ? ((double)value * Double.Parse(parameter.ToString())) : Double.NaN;
            //                return Double.NaN;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            return value;
        }

        #endregion
    }
    #endregion
}

